package cn.lanqiao.bigDate.web;

import cn.lanqiao.bigDate.entity.sys.SysMenu;
import cn.lanqiao.bigDate.entity.sys.SysUser;
import cn.lanqiao.bigDate.reslut.SystemHardwareInfo;
import cn.lanqiao.bigDate.service.img.Captcha;
import cn.lanqiao.bigDate.web.security.Security;
import cn.lanqiao.common.constant.UtilConstants;
import cn.lanqiao.common.utils.TokenUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.imageio.ImageIO;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Random;


@Controller
public class PageController extends BaseController {
	public static final Random r=new Random();
	@Security
	@RequestMapping(value="/success")
//	public ModelAndView success(@CookieValue(name = "Authorization") String auth, HttpServletResponse response) throws IOException {
	public ModelAndView success( HttpServletResponse response) throws IOException {
		ModelAndView mav = new ModelAndView();
//		if(auth==null||auth.trim().length()==0){
//			response.sendRedirect("/bigDateWeb/toLogin");
//		}
		SysUser sysUser = sysUserService.findSysUserOne(2l);
		List<SysMenu> menuList = sysMenuService.findAllSysMenu();
		mav.addObject("menuList",menuList);
		mav.addObject("sysUser",sysUser);
		mav.setViewName("main/admin");
		return mav;
	}



	@RequestMapping(value = "verifiCode", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
	public   void verifiCode(HttpServletRequest request,HttpServletResponse response) {
		String verifyTime=request.getParameter("t");
		ServletOutputStream out;
		try {
			Captcha captcha=imageService.getImageHeigh(4);
			out = response.getOutputStream();
			String code=captcha.getStringBuilder().toString();
			//将验证码存储到缓存
			stringRedisTemplate.opsForValue().set(verifyTime,code);
			stringRedisTemplate.expire(verifyTime,10,TimeUnit.MINUTES);
			ImageIO.write(captcha.getImage(), "JPG", out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Security
	@RequestMapping(value="welcome")
	public ModelAndView left(@CookieValue("Authorization") String auth, HttpServletRequest request, ModelMap modelMap){
		SysUser sysUser = sysUserService.findSysUserOne(TokenUtil.getUserName(auth.substring(7)));
		SystemHardwareInfo info = new SystemHardwareInfo();
		ModelAndView mav = new ModelAndView();
		mav.addObject("info",info);
		mav.addObject("sysUser",sysUser);
		mav.setViewName("main/welcome");
		return mav;
	}


	@RequestMapping(value="/pageError")
	public ModelAndView pageError(String errorNumber){
		ModelAndView mav =new ModelAndView();
		mav.setViewName(errorNumber);
		return mav;
	}

}
